import requests,json,sys
from lxml import etree
from urllib.parse import quote
from main import Book


class SearchBook():
    def __init__(self, keyword):
        self.search_url = f'https://www.bqgka.com/user/search.html?q={keyword}'
        # print(self.search_url)
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
        }

    def get_book_info(self):
        r = requests.get(self.search_url,headers=self.headers,allow_redirects=True)
        # print(r.text)
        if r.status_code == 200:
            datas = json.loads(r.text)
            # for index,data in enumerate(datas,start=1):
            #     book_name = data.get('articlename','未知')
            #     print(f'序号:{index}',book_name)
            # print(datas)
            return datas
        else:
            print('请求失败:',r.status_code)
            return None


    def select_book(self):
        # bdatas = self.get_book_info()
        # print(type(bdatas))
        maxretries = 3
        retries = 0
        while retries < maxretries:
            # self.keyword = quote(input('请重试搜索的书籍:'))
            bdatas = self.get_book_info()
            # print(bdatas)
            try:
                for i,data in enumerate(bdatas,start=1):
                    book_name = data.get('articlename', '未知')
                    print(f'{i}.{book_name}')
                index = int(input('请选择要下载的序号:'))
                if 1 <= index <= len(bdatas):
                    url_list = bdatas[index-1].get('url_list','未知')
                    # print(url_list)
                    return url_list
                else:
                    print('请输入正确的序号')
                    return None
            except:
                if str(1) == str(bdatas):
                    user_input = input('暂未搜索到，请重新输入：')
                    self.new_input = quote(user_input)
                    # print(self.new_input)
                    self.search_url = f'https://www.bqgka.com/user/search.html?q={self.new_input}'
                    # print(self.search_url)
                    retries += 1
                    # print(f'重新搜索，重试次数：{retries}')
                    continue
                # print('下载出错了，请再重试一次吧')
                # break
        print('重试次数过多已被限制访问，请稍后再试')
        sys.exit()








if __name__ == '__main__':
    keyword = input('请输入要搜索的书名：')
    zkeyword = quote(keyword)
    # print(zkeyword)
    s = SearchBook(zkeyword)
    # s.get_book_info()
    base_url = s.select_book()
    # print(base_url)
    b = Book(keyword)
    b.get_html_info(base_url=base_url)
    b.get_one_chapter()


